package gitop

import (
  "fmt"
	"time"
  "os"

  git "github.com/go-git/go-git/v5"
  . "github.com/go-git/go-git/v5/_examples"
	"github.com/go-git/go-git/v5/plumbing"
  "github.com/go-git/go-git/v5/plumbing/object"
  _ "github.com/go-git/go-git/v5/storage/memory"
)

func Get(gitUrl string) {
	// Clone the given repository to the given directory
  Info("git clone "+gitUrl)

  r, err := git.PlainClone("./gitlab/demo", false, &git.CloneOptions{
	  	// URL: "https://github.com/src-d/go-siva",
      URL: gitUrl,
      Progress: os.Stdout,
  })
  // r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{
	// 	URL: "https://github.com/src-d/go-siva",
  //   Progress: os.Stdout,
  // }) 

  CheckIfError(err)

	// ... retrieving the commit being pointed by HEAD
	Info("git show-ref --head HEAD")
	ref, err := r.Head()
	CheckIfError(err)
	fmt.Println(ref.Hash())

	w, err := r.Worktree()
	CheckIfError(err)

	// ... checking out to commit
	Info("git checkout master")
	err = w.Checkout(&git.CheckoutOptions{
		Hash: plumbing.NewHash("master"),
	})
	CheckIfError(err)


  // Gets the HEAD history from HEAD, just like this command:
	Info("git log")

	// ... retrieves the branch pointed by HEAD
	ref2, err := r.Head()
	CheckIfError(err)

	// ... retrieves the commit history
	since := time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC)
	until := time.Date(2021, 7, 30, 0, 0, 0, 0, time.UTC)
	cIter, err := r.Log(&git.LogOptions{From: ref2.Hash(), Since: &since, Until: &until})
	CheckIfError(err)


	// ... just iterates over the commits, printing it
	err = cIter.ForEach(func(c *object.Commit) error {
		fmt.Println(c)

		return nil
	})
	CheckIfError(err)
}